package com.aaie.gru.notice.controller;


import com.aaie.gru.login.entity.LoginUser;
import com.aaie.gru.notice.entity.GruSysNotice;
import com.aaie.gru.notice.entity.GruSysNoticeDto;
import com.aaie.gru.notice.service.IGruSysNoticeService;
import com.aaie.gru.response.ResMessage;
import com.aaie.gru.util.CommonUtil;
import com.aaie.gru.util.ExceptionEnums;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fanwei.meng
 * @since 2019-08-23
 */
@Api(tags = "公告模块")
@RestController
@RequestMapping("/notice")
public class GruSysNoticeController {

    private static final Logger logger = LoggerFactory.getLogger(GruSysNoticeController.class);

    @Autowired
    IGruSysNoticeService iGruSysNoticeService;

    /**
     * 获取公告列表
     *
     * @param param
     * @return
     */
    @ApiOperation(value = "获取公告列表", notes = "获取公告列表")
    @PostMapping("/getGruSysNoticeList")
    public String getGruSysNoticeList(@RequestBody GruSysNoticeDto param) {
        try {
            // 定义分页
            Page<GruSysNotice> paramPage = new Page<>(param.getCurrent(), param.getSize());
            // 查询条件
            QueryWrapper<GruSysNotice> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(param.getSearch())) {
                queryWrapper.and(qw -> qw.like("notice_title", param.getSearch())
                        .or().like("notice_content", param.getSearch()));
            }
            // 按更新时间倒叙排序
            queryWrapper.orderByDesc("update_time_sort");
            IPage<GruSysNotice> page = iGruSysNoticeService.page(paramPage, queryWrapper);
            return ResMessage.ok(page.getRecords(), param.getCurrent(), param.getSize(), page.getTotal());
        } catch (BeansException e) {
            logger.error("=========>>>>>>>>>>>/notice/getGruSysNoticeList 入参:" + JSONObject.toJSONString(param));
            return ResMessage.error("/notice/getGruSysNoticeList报错", 500);
        }
    }

    /**
     * 新增公告
     *
     * @param gruSysNotice
     * @param session
     * @return
     */
    @ApiOperation(value = "新增公告", notes = "新增公告")
    @PostMapping("/addGruSysNotice")
    public String addGruSysNotice(@RequestBody GruSysNotice gruSysNotice, HttpSession session) {
        try {
            if (StringUtils.isNotEmpty(gruSysNotice.getNoticeId())) {
                return ResMessage.error(ExceptionEnums.ADD_DATA_NO_PRI.getEmsg(), ExceptionEnums.ADD_DATA_NO_PRI.getEcode());
            }
            //公告标题不能为空
            String noticeTitlStr = gruSysNotice.getNoticeTitle();
            if (StringUtils.isEmpty(noticeTitlStr)) {
                return ResMessage.error(ExceptionEnums.NOTICE_TITLE_NO_EMPTY.getEmsg(), ExceptionEnums.NOTICE_TITLE_NO_EMPTY.getEcode());
            }

            String updateTime = CommonUtil.generateLocalDateTime();
            long updateTimeSort = CommonUtil.generateCurrentTimeMillis();
            LoginUser loginUser = CommonUtil.getUser(session);
            if (loginUser == null) {
                return ResMessage.error(ExceptionEnums.LOGINUSER_IS_NULL.getEmsg(), ExceptionEnums.LOGINUSER_IS_NULL.getEcode());
            } else {
                gruSysNotice.setCreateName(CommonUtil.getUser(session).getUserName());
                gruSysNotice.setCreateTime(updateTime);
                gruSysNotice.setCreateTimeSort(updateTimeSort);
                gruSysNotice.setUpdateName(CommonUtil.getUser(session).getUserName());
                gruSysNotice.setUpdateTime(updateTime);
                gruSysNotice.setUpdateTimeSort(updateTimeSort);
            }

            boolean result = iGruSysNoticeService.save(gruSysNotice);
            if (!result) {
                return ResMessage.error(ExceptionEnums.DATA_INSERT_ERROR.getEmsg(), ExceptionEnums.DATA_INSERT_ERROR.getEcode());
            }
        } catch (Exception e) {
            logger.error("=========>>>>>>>>>>>/notice/addNotice:" + e.getMessage() + "【入参】" + JSONObject.toJSONString(gruSysNotice));
            return ResMessage.error(ExceptionEnums.SYSTEM_ERROR.getEmsg(), ExceptionEnums.SYSTEM_ERROR.getEcode());
        }
        return ResMessage.ok(gruSysNotice);
    }

    @ApiOperation(value = "更新公告", notes = "更新公告")
    @PostMapping("/editGruSysNotice")
    public String editGruSysNotice(@RequestBody GruSysNotice gruSysNotice, HttpSession session) {
        try {
            if (StringUtils.isEmpty(gruSysNotice.getNoticeId())) {
                return ResMessage.error(ExceptionEnums.ADD_DATA_NEED_PRI.getEmsg(), ExceptionEnums.ADD_DATA_NEED_PRI.getEcode());
            }
            // 创建人只能取用户账号，不取用户名称了，因为用户名称不是同一个字段，取起来太麻烦
            LoginUser loginUser = CommonUtil.getUser(session);
            if (loginUser == null) {
                return ResMessage.error(ExceptionEnums.LOGINUSER_IS_NULL.getEmsg(), ExceptionEnums.LOGINUSER_IS_NULL.getEcode());
            } else {
                gruSysNotice.setUpdateName(CommonUtil.getUser(session).getUserName());
                gruSysNotice.setUpdateTime(CommonUtil.generateLocalDateTime());
                gruSysNotice.setUpdateTimeSort(CommonUtil.generateCurrentTimeMillis());
            }

            boolean result = iGruSysNoticeService.updateById(gruSysNotice);
            if (!result) {
                return ResMessage.error(ExceptionEnums.DATA_UPDATE_ERROR.getEmsg(), ExceptionEnums.DATA_UPDATE_ERROR.getEcode());
            }
            return ResMessage.ok(gruSysNotice);
        } catch (Exception e) {
            logger.error("=========>>>>>>>>>>>/notice/editGruSysPay:" + e.getMessage() + "【入参】" + JSONObject.toJSONString(gruSysNotice));
            return ResMessage.error(ExceptionEnums.SYSTEM_ERROR.getEmsg(), ExceptionEnums.SYSTEM_ERROR.getEcode());
        }
    }

    @ApiOperation(value = "删除公告", notes = "删除公告")
    @PostMapping("/delGruSysNotice")
    public String delGruSysNotice(@RequestBody GruSysNotice gruSysNotice) {
        try {
            if (StringUtils.isEmpty(gruSysNotice.getNoticeId())) {
                return ResMessage.error(ExceptionEnums.ADD_DATA_NEED_PRI.getEmsg(), ExceptionEnums.ADD_DATA_NEED_PRI.getEcode());
            }

            boolean result = iGruSysNoticeService.removeById(gruSysNotice.getNoticeId());
            if (result) {
                return ResMessage.ok(ExceptionEnums.DATA_DELETE_SUCCESS.getEmsg());
            } else {
                return ResMessage.error(ExceptionEnums.DATA_DELETE_ERROR.getEmsg(), ExceptionEnums.DATA_DELETE_ERROR.getEcode());
            }
        } catch (Exception e) {
            logger.error("=========>>>>>>>>>>>/notice/delGruSysNotice:" + e.getMessage() + "【入参】" + JSONObject.toJSONString(gruSysNotice));
            return ResMessage.error(ExceptionEnums.SYSTEM_ERROR.getEmsg(), ExceptionEnums.SYSTEM_ERROR.getEcode());
        }
    }

    @ApiOperation(value = "获取公告详情", notes = "获取公告详情")
    @GetMapping("/getGruSysNotice")
    public String getGruSysNotice(String noticeId) {
        try {
            if (StringUtils.isEmpty(noticeId)) {
                return ResMessage.error(ExceptionEnums.ADD_DATA_NEED_PRI.getEmsg(), ExceptionEnums.ADD_DATA_NEED_PRI.getEcode());
            }
            GruSysNotice gruSysNotice = iGruSysNoticeService.getById(noticeId);
            return ResMessage.ok(gruSysNotice);
        } catch (Exception e) {
            logger.error("=========>>>>>>>>>>>/notice/getGruSysNotice:" + e.getMessage() + "【入参】" + JSONObject.toJSONString(noticeId));
            return ResMessage.error(ExceptionEnums.SYSTEM_ERROR.getEmsg(), ExceptionEnums.SYSTEM_ERROR.getEcode());
        }
    }
}
